
//210.课程表II
class Solution {
public:
    vector<int> findOrder(int numCourses, vector<vector<int>>& nums) {
        //进行优化

        vector<int> ret;
        vector<int> each(numCourses);
        queue<int> q;       //记录可以学习的课程
        unordered_map<int,vector<int>> m;
        for(auto& tmp: nums)
        {
            each[tmp[0]]++;
            m[tmp[1]].push_back(tmp[0]);
        }    
        
        for(int i=0;i<numCourses;i++) 
            if(!each[i]) q.push(i);     //将可以学习的课程入队列

        while(!q.empty())
        {
            int _sz=q.size();
            for(int i=0;i<_sz;i++)
            {
                int x=q.front();
                q.pop();
                ret.push_back(x);
                auto& tmp=m[x];
                for(int i=0;i<tmp.size();i++)
                    if(--each[tmp[i]]==0) q.push(tmp[i]);
            }
        }
        if(ret.size()==numCourses) return ret;
        else return {};
    }
};